import datetime
from typing import List

import requests
from fastapi import Depends
from sqlalchemy.orm import Session

from config.database import SessionLocal
from config.get_db import get_db
from core.dao.cms_alert_message_dao import CmsAlertMessageDao
from core.dao.cms_gaode_fence_terminal_dao import CmsGaodeFenceTerminalDao
from core.dao.cms_terminal_point_dao import CmsTerminalPointDao
from core.entity.do.models import CmsGaodeFenceTerminal
from core.entity.vo.view_models import CarModelForAll, CmsAlertMessageVO, CarModelForAllTrack, CmsCarTrackVO
from core.service.cms_alert_message_service import CmsAlertMessageService
from core.service.cms_car_service import CmsCarService
from core.service.cms_car_track_service import CmsCarTrackService
from core.service.gaode.gaode_dili_service import GaodeDiLiService
from core.service.gaode.gaode_fence_terminal_service import GaodeFenceTerminalService
from utils.uuid import UUID


class AlertMessageService:
    @classmethod
    def add_message(cls):
        db = SessionLocal()
        print("被调用了")
        # 查询出所有车辆集合
        try:
            uuid = UUID()
            list_all_car_running: List[CarModelForAll] = CmsCarService.get_cms_car_list_all(db)
            for e in list_all_car_running:
                # 查询车辆当前经纬度
                if e.device_id is None:
                    continue
                terminal_point = CmsTerminalPointDao.get_cms_terminal_point_by_terminal_id_last_one(db, e.device_id)
                if terminal_point is None or terminal_point.lon is None or terminal_point.lat is None:
                    continue
                # 查询车辆是否进入监控区域
                status = GaodeFenceTerminalService.query_fence_location_status("1033614",
                                                                               terminal_point.lon + "," +
                                                                               terminal_point.lat,
                                                                               e.fence_id)
                if 'errcode' in status and status['errcode'] == 10000:
                    ter: CmsGaodeFenceTerminal = CmsGaodeFenceTerminalDao.get_cms_gaode_fence_terminal_by_fence_id_and_ter(
                        db, e.fence_id, e.car_id)
                    in_ = status['data']['results'][0]['in']
                    vo = CmsAlertMessageVO()
                    vo.id = int(uuid.uuid())
                    vo.fence_id = e.fence_id
                    vo.fence_name = e.fence_name
                    vo.car_id = e.car_id
                    vo.car_number = e.car_number
                    vo.state = 1
                    if ter and e.alarm_type == '进入监控' and ter.update_by == '0' and in_ == 1:
                        vo.alert_type = '进入监控'
                        vo.alert_msg = '进入监控'
                        cls.method_name(terminal_point, vo)
                        CmsAlertMessageDao.add_cms_alert_message_dao(db, vo)
                    if ter and e.alarm_type == '离开监控' and ter.update_by == '1' and in_ == 0:
                        vo.alert_type = '离开监控'
                        vo.alert_msg = '离开监控'
                        # 查询当前位置
                        cls.method_name(terminal_point, vo)
                        CmsAlertMessageService.add_cms_alert_message(db, vo)
                    if ter and status['data']['results'][0]['in'] is not None:
                        ter.update_by = status['data']['results'][0]['in']
                        CmsGaodeFenceTerminalDao.add_cms_gaode_fence_terminal(db, ter)
            db.commit()
        except Exception as e:
            db.rollback()
            raise ValueError(e)
        finally:
            db.close()

    @classmethod
    def method_name(cls, terminal_point, vo):
        # 查询当前位置
        address = GaodeDiLiService.get_address(terminal_point.lon + "," + terminal_point.lat)
        if 'status' in address and address['status'] == '1':
            component_ = address['regeocode']['addressComponent']
            list = []
            address = ""
            i = 0
            list.append(component_['country'])
            list.append(component_['province'])
            list.append(component_['city'])
            list.append(component_['township'])
            for location in list:
                if location is not None and len(location) != 0:
                    address = address + location
                    i = i + 1
                    if i != len(list):
                        address = address + ","
            vo.location = address


    @classmethod
    def upload_point(cls):
        db = SessionLocal()
        print(f"{datetime.datetime.now()}被调用了")
        # 查询出所有车辆集合
        try:
            uuid = UUID()
            list_all_car_running: List[CarModelForAllTrack] = CmsCarService.get_cms_car_list_all_track(db)
            for e in list_all_car_running:
                # 上传轨迹
                track_vo = CmsCarTrackVO(**e.__dict__)
                uuid_uuid = uuid.uuid()
                track_vo.id = uuid_uuid
                track_vo.record_time = datetime.datetime.now()
                track_vo.track_id = "tra_" + uuid_uuid
                track_vo.gaode_track_id = None
                track_vo.track_name = track_vo.track_id
                track_vo.state = 1
                CmsCarTrackService.add_cms_car_track(db, track_vo)
            db.commit()
        except Exception as e:
            db.rollback()
            raise ValueError(e)
        finally:
            db.close()